//
//  SignUpViewController.swift
//  worldexchange
//
//  Created by xionghao on 2019/1/10.
//  Copyright © 2019 xionghao. All rights reserved.
//

import UIKit

class SignUpViewController: QMUICommonViewController {

    @IBOutlet weak var userWrapper: UIView!
    @IBOutlet weak var passwordWrapper: UIView!
    @IBOutlet weak var confirmWrapper: UIView!
    @IBOutlet weak var emailWrapper: UIView!
    @IBOutlet weak var validateWrapper: UIView!
    @IBOutlet weak var nameWrapper: UIView!
    
    @IBOutlet weak var tf_phone: UITextField!
    @IBOutlet weak var phoneWrapper: UIView!
    @IBOutlet weak var btnGetValidate: UIButton!
    @IBOutlet weak var btnRegister: QMUIFillButton!
    @IBOutlet weak var tf_username: UITextField!
    @IBOutlet weak var tf_password: UITextField!
    @IBOutlet weak var tf_confirm: UITextField!
    @IBOutlet weak var tf_email: UITextField!
    @IBOutlet weak var tf_code: UITextField!

    @IBOutlet weak var tf_name: UITextField!
    @IBOutlet weak var btnCountryCode: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "SignUp".localized()

        self.btnRegister.setTitle(self.title, for: UIControl.State.normal)
        
        userWrapper.qmui_borderColor = UIColor.qmui_color(withHexString: "#d5d5d5")
        userWrapper.qmui_borderWidth = 0.5
        userWrapper.qmui_borderPosition = .bottom
        
        passwordWrapper.qmui_borderColor = UIColor.qmui_color(withHexString: "#d5d5d5")
        passwordWrapper.qmui_borderWidth = 0.5
        passwordWrapper.qmui_borderPosition = .bottom
        
        confirmWrapper.qmui_borderColor = UIColor.qmui_color(withHexString: "#d5d5d5")
        confirmWrapper.qmui_borderWidth = 0.5
        confirmWrapper.qmui_borderPosition = .bottom
        
        emailWrapper.qmui_borderColor = UIColor.qmui_color(withHexString: "#d5d5d5")
        emailWrapper.qmui_borderWidth = 0.5
        emailWrapper.qmui_borderPosition = .bottom
        
        validateWrapper.qmui_borderColor = UIColor.qmui_color(withHexString: "#d5d5d5")
        validateWrapper.qmui_borderWidth = 0.5
        validateWrapper.qmui_borderPosition = .bottom
        
        phoneWrapper.qmui_borderColor = UIColor.qmui_color(withHexString: "#d5d5d5")
        phoneWrapper.qmui_borderWidth = 0.5
        phoneWrapper.qmui_borderPosition = .bottom
        
        nameWrapper.qmui_borderColor = UIColor.qmui_color(withHexString: "#d5d5d5")
        nameWrapper.qmui_borderWidth = 0.5
        nameWrapper.qmui_borderPosition = .bottom
        
        self.tf_username.placeholder = "InputUserName".localized()
        self.tf_phone.placeholder = "InputPhone".localized()
        self.tf_password.placeholder = LanguageHelper.getString(key: "InputPassword")
        self.tf_confirm.placeholder = LanguageHelper.getString(key: "InputConfirm")
        self.tf_email.placeholder = LanguageHelper.getString(key: "InputEmail")
        self.tf_code.placeholder = LanguageHelper.getString(key: "InputCode")
        self.tf_name.placeholder = LanguageHelper.getString(key: "InputName")
        self.btnGetValidate.setTitle(LanguageHelper.getString(key: "btnGetValidate"), for: UIControl.State.normal)
        
        // Do any additional setup after loading the view.
    }

    @IBAction func btnCountryCodeClick(_ sender: UIButton) {
        self.changeCountryCode()
    }
    
    func changeCountryCode() {
        
        let countryCodes = [LanguageHelper.getString(key: "textChina"),LanguageHelper.getString(key: "textThailand")]
        let dialogViewController = QMUIDialogSelectionViewController()
        let codes = ["+86","+66"]
        
        dialogViewController.title = nil
        dialogViewController.items = countryCodes
        dialogViewController.cellForItemBlock = { aDialogViewController, cell, itemIndex in
            cell?.accessoryType = UITableViewCell.AccessoryType.none // 移除点击时默认加上右边的checkbox
        }
        dialogViewController.heightForItemBlock = { aDialogViewController, itemIndex in
            return 54 // 修改默认的行高，默认为 TableViewCellNormalHeight
        }
        dialogViewController.didSelectItemBlock = { aDialogViewController, itemIndex in
            aDialogViewController?.hide()
            let code = codes[Int(itemIndex)]
            self.btnCountryCode.setTitle(code, for: UIControl.State.normal)
            
        }
        dialogViewController.show()


    }

    @IBAction func btnGetValidate(_ sender: UIButton) {
        if !Validate.email(self.tf_email.text ?? "").isRight {
            QMUITips.show(withText: LanguageHelper.getString(key: "EmailError"))
            return
        }
        if self.tf_phone.text == "" {
            QMUITips.show(withText: LanguageHelper.getString(key: "InputPhone"))
            return
        }
        
        QMUITips.showLoading(in: self.view)
        
     
        let phone = "\(self.btnCountryCode.titleLabel!.text)\(self.tf_phone.text!)" ?? "+86\(self.tf_phone.text!)"
 QMUITips.showLoading(in: self.view)
        
            provider.rx.request(WE.email(email: self.tf_email.text!,phone: phone)).filterSuccessfulStatusCodes().mapString().subscribe(onSuccess: { (result) in
                QMUITips.hideAllTips()
                if let apiResult =  ApiResult.deserialize(from: result) {
                    if apiResult.code != 200 {
                        QMUITips.show(withText: apiResult.message)
                    } else {
                        self.countDown()
                    }
                }
               
               


            }) { ( e) in
                print(e)
                QMUITips.show(withText: LanguageHelper.getString(key: "network error"))
            }
        
    }


    func countDown() {
        self.btnGetValidate.isEnabled = false
        Utils.timer(duration: 90, interval: 1, ascending: false).subscribe(onNext: { (count) in
            self.btnGetValidate.setTitle("\(count)S", for: UIControl.State.normal)

        }, onError: { (_) in

        }, onCompleted: {
            self.btnGetValidate.isEnabled = true
            self.btnGetValidate.setTitle(LanguageHelper.getString(key: "reSendValidate"), for: UIControl.State.normal)
        }) {

        }
    }


    @IBAction func registerClick(_ sender: QMUIFillButton) {
        if self.tf_username.text == "" {
            QMUITips.show(withText: LanguageHelper.getString(key: "usernameEmpty"))
            return
        }
        if self.tf_password.text == "" {
            QMUITips.show(withText: LanguageHelper.getString(key: "passwordEmpty"))
            return
        }
        if self.tf_phone.text == "" {
            QMUITips.show(withText: LanguageHelper.getString(key: "InputPhone"))
            return
        }
        
        if self.tf_name.text == "" {
            QMUITips.show(withText: LanguageHelper.getString(key: "InputName"))
            return
        }

        if self.tf_confirm.text == "" {
            QMUITips.show(withText: LanguageHelper.getString(key: "confirmEmpty"))
            return
        }

        if self.tf_confirm.text != self.tf_password.text {
            QMUITips.show(withText: LanguageHelper.getString(key: "passwordIsNotSame"))
            return
        }

        if !Validate.email(self.tf_email.text ?? "").isRight {
            QMUITips.show(withText: LanguageHelper.getString(key: "EmailError"))
            return
        }

        if self.tf_code.text == "" {
            QMUITips.show(withText: LanguageHelper.getString(key: "validateEmpty"))
            return
        }

        self.tf_password.endEditing(true)
        self.tf_username.endEditing(true)
        self.tf_confirm.endEditing(true)
        self.tf_code.endEditing(true)
        self.tf_email.endEditing(true)

        self.registerAction()

    }

    func registerAction() {
        QMUITips.showLoading(in: self.navigationController!.view)
        provider.rx.request(WE.register(username: self.tf_username.text!, password: self.tf_password.text!,name: self.tf_name.text!,phone: self.tf_phone.text!, email: self.tf_email.text!, code: self.tf_code.text!)).filterSuccessfulStatusCodes().mapString().subscribe(onSuccess: { (result) in
            if let loginResult = LoginReuslt.deserialize(from: result) {
                if loginResult.code == 200 {
                    isLogin = true
                    userData = loginResult.data
                    QMUITips.hideAllTips(in: self.navigationController!.view)
                    QMUITips.showSucceed(LanguageHelper.getString(key: "LoginSuccess"))
                    NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "UserLoginChange"), object: nil)
                    self.navigationController?.dismiss(animated: true, completion: {

                    })
                } else {
                    QMUITips.hideAllTips(in: self.navigationController!.view)
                    QMUITips.show(withText: loginResult.message)
                }
            } else {
                QMUITips.hideAllTips(in: self.navigationController!.view)
            }
        }) { (error) in
            print(error)
            QMUITips.hideAllTips(in: self.navigationController!.view)
            QMUITips.show(withText: "network error!")
        }
    }

    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */

}
